{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 0
   },
   "source": [
    "# Calculus\n",
    ":label:`sec_calculus`\n",
    "\n",
    "Finding the area of a polygon had remained mysterious\n",
    "until at least 2,500 years ago, when ancient Greeks divided a polygon into triangles and summed their areas.\n",
    "To find the area of curved shapes, such as a circle,\n",
    "ancient Greeks inscribed polygons in such shapes.\n",
    "As shown in :numref:`fig_circle_area`,\n",
    "an inscribed polygon with more sides of equal length better approximates\n",
    "the circle. This process is also known as the *method of exhaustion*.\n",
    "\n",
    "![Find the area of a circle with the method of exhaustion.](https://raw.githubusercontent.com/d2l-ai/d2l-en/master/img/polygon-circle.svg)\n",
    ":label:`fig_circle_area`\n",
    "\n",
    "In fact, the method of exhaustion is where *integral calculus* (will be described in :numref:`sec_integral_calculus`) originates from.\n",
    "More than 2,000 years later,\n",
    "the other branch of calculus, *differential calculus*,\n",
    "was invented.\n",
    "Among the most critical applications of differential calculus,\n",
    "optimization problems consider how to do something *the best*.\n",
    "As discussed in :numref:`subsec_norms_and_objectives`,\n",
    "such problems are ubiquitous in deep learning.\n",
    "\n",
    "In deep learning, we *train* models, updating them successively\n",
    "so that they get better and better as they see more and more data.\n",
    "Usually, getting better means minimizing a *loss function*,\n",
    "a score that answers the question \"how *bad* is our model?\"\n",
    "This question is more subtle than it appears.\n",
    "Ultimately, what we really care about\n",
    "is producing a model that performs well on data\n",
    "that we have never seen before.\n",
    "But we can only fit the model to data that we can actually see.\n",
    "Thus we can decompose the task of fitting models into two key concerns:\n",
    "i) *optimization*: the process of fitting our models to observed data;\n",
    "ii) *generalization*: the mathematical principles and practitioners' wisdom\n",
    "that guide as to how to produce models whose validity extends\n",
    "beyond the exact set of data examples used to train them.\n",
    "\n",
    "To help you understand\n",
    "optimization problems and methods in later chapters,\n",
    "here we give a very brief primer on differential calculus\n",
    "that is commonly used in deep learning.\n",
    "\n",
    "\n",
    "## Derivatives and Differentiation\n",
    "\n",
    "We begin by addressing the calculation of derivatives,\n",
    "a crucial step in nearly all deep learning optimization algorithms.\n",
    "In deep learning, we typically choose loss functions\n",
    "that are differentiable with respect to our model's parameters.\n",
    "Put simply, this means that for each parameter,\n",
    "we can determine how rapidly the loss would increase or decrease,\n",
    "were we to *increase* or *decrease* that parameter\n",
    "by an infinitesimally small amount.\n",
    "\n",
    "Suppose that we have a function $f: \\mathbb{R} \\rightarrow \\mathbb{R}$,\n",
    "whose input and output are both scalars.\n",
    "The *derivative* of $f$ is defined as\n",
    "\n",
    "$$f'(x) = \\lim_{h \\rightarrow 0} \\frac{f(x+h) - f(x)}{h},$$\n",
    ":eqlabel:`eq_derivative`\n",
    "\n",
    "if this limit exists.\n",
    "If $f'(a)$ exists,\n",
    "$f$ is said to be *differentiable* at $a$.\n",
    "If $f$ is differentiable at every number of an interval,\n",
    "then this function is differentiable on this interval.\n",
    "We can interpret the derivative $f'(x)$ in :eqref:`eq_derivative`\n",
    "as the *instantaneous* rate of change of $f(x)$\n",
    "with respect to $x$.\n",
    "The so-called instantaneous rate of change is based on\n",
    "the variation $h$ in $x$, which approaches $0$.\n",
    "\n",
    "To illustrate derivatives,\n",
    "let us experiment with an example.\n",
    "Define $u = f(x) = 3x^2-4x$.\n",
    "\n",
    "*Note: We will be using Double in this section to avoid incorrect results since Double provides more decimal precision. Generally though, we would use Float as deep learning frameworks by default use Fault.*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "// %mavenRepo snapshots https://oss.sonatype.org/content/repositories/snapshots/\n",
    "\n",
    "%maven ai.djl:api:0.9.0\n",
    "%maven org.slf4j:slf4j-api:1.7.26\n",
    "%maven org.slf4j:slf4j-simple:1.7.26\n",
    "\n",
    "%maven ai.djl.mxnet:mxnet-engine:0.9.0\n",
    "%maven ai.djl.mxnet:mxnet-native-auto:1.7.0-backport"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load ../utils/plot-utils\n",
    "%load ../utils/Functions.java"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import ai.djl.ndarray.*;\n",
    "import tech.tablesaw.plotly.traces.*;\n",
    "import tech.tablesaw.plotly.components.*;\n",
    "import ai.djl.ndarray.types.DataType;"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NDManager manager = NDManager.newBaseManager();"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Function<Double, Double> f = x -> (3 * Math.pow(x, 2) -4 * x);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 4
   },
   "source": [
    "By setting $x=1$ and letting $h$ approach $0$,\n",
    "the numerical result of $\\frac{f(x+h) - f(x)}{h}$\n",
    "in :eqref:`eq_derivative` approaches $2$.\n",
    "Though this experiment is not a mathematical proof,\n",
    "we will see later that the derivative $u'$ is $2$ when $x=1$.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public Double numericalLim(Function<Double, Double> f, double x, double h) {\n",
    "    return (f.apply(x+h) - f.apply(x)) / h;\n",
    "}\n",
    "\n",
    "double h = 0.1;\n",
    "for (int i=0; i < 5; i++) {\n",
    "    System.out.println(\"h=\" + String.format(\"%.5f\", h) + \", numerical limit=\" \n",
    "                       + String.format(\"%.5f\", numericalLim(f, 1, h)));\n",
    "    h *= 0.1;\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 6
   },
   "source": [
    "Let us familiarize ourselves with a few equivalent notations for derivatives.\n",
    "Given $y = f(x)$, where $x$ and $y$ are the independent variable and the dependent variable of the function $f$, respectively. The following expressions are equivalent:\n",
    "\n",
    "$$f'(x) = y' = \\frac{dy}{dx} = \\frac{df}{dx} = \\frac{d}{dx} f(x) = Df(x) = D_x f(x),$$\n",
    "\n",
    "where symbols $\\frac{d}{dx}$ and $D$ are *differentiation operators* that indicate operation of *differentiation*.\n",
    "We can use the following rules to differentiate common functions:\n",
    "\n",
    "* $DC = 0$ ($C$ is a constant),\n",
    "* $Dx^n = nx^{n-1}$ (the *power rule*, $n$ is any real number),\n",
    "* $De^x = e^x$,\n",
    "* $D\\ln(x) = 1/x.$\n",
    "\n",
    "To differentiate a function that is formed from a few simpler functions such as the above common functions,\n",
    "the following rules can be handy for us.\n",
    "Suppose that functions $f$ and $g$ are both differentiable and $C$ is a constant,\n",
    "we have the *constant multiple rule*\n",
    "\n",
    "$$\\frac{d}{dx} [Cf(x)] = C \\frac{d}{dx} f(x),$$\n",
    "\n",
    "the *sum rule*\n",
    "\n",
    "$$\\frac{d}{dx} [f(x) + g(x)] = \\frac{d}{dx} f(x) + \\frac{d}{dx} g(x),$$\n",
    "\n",
    "the *product rule*\n",
    "\n",
    "$$\\frac{d}{dx} [f(x)g(x)] = f(x) \\frac{d}{dx} [g(x)] + g(x) \\frac{d}{dx} [f(x)],$$\n",
    "\n",
    "and the *quotient rule*\n",
    "\n",
    "$$\\frac{d}{dx} \\left[\\frac{f(x)}{g(x)}\\right] = \\frac{g(x) \\frac{d}{dx} [f(x)] - f(x) \\frac{d}{dx} [g(x)]}{[g(x)]^2}.$$\n",
    "\n",
    "Now we can apply a few of the above rules to find\n",
    "$u' = f'(x) = 3 \\frac{d}{dx} x^2-4\\frac{d}{dx}x = 6x-4$.\n",
    "Thus, by setting $x = 1$, we have $u' = 2$:\n",
    "this is supported by our earlier experiment in this section\n",
    "where the numerical result approaches $2$.\n",
    "This derivative is also the slope of the tangent line\n",
    "to the curve $u = f(x)$ when $x = 1$.\n",
    "\n",
    "To visualize such an interpretation of derivatives,\n",
    "we will use `plotly`,\n",
    "a popular plotting library.\n",
    "`Tablesaw` has implemented a Java wrapper for `plotly` so we will be using that framework.\n",
    "To configure the properties and plot the figures produced by `plotly`,\n",
    "we will define one function.\n",
    "\n",
    "We define `plotLineAndSegment` which will take as input \n",
    "three arrays. The first array will be the data in the x \n",
    "axis and the next two arrays will contain the two functions \n",
    "that we want to plot in the y axis. In addition to this data, \n",
    "the function requires us to specify the name of the two lines \n",
    "we will be plotting, the label of both axes, and the width and\n",
    "height of the figure. This function or a modified version \n",
    "of it, will allow us to plot multiple curves succinctly\n",
    "since we will need to visualize many curves throughout the book."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public Figure plotLineAndSegment(double[] x, double[] y, double[] segment,\n",
    "                                 String trace1Name, String trace2Name,\n",
    "                                 String xLabel, String yLabel,\n",
    "                                 int width, int height) {\n",
    "    ScatterTrace trace = ScatterTrace.builder(x, y)\n",
    "        .mode(ScatterTrace.Mode.LINE)\n",
    "        .name(trace1Name)\n",
    "        .build();\n",
    "    \n",
    "    ScatterTrace trace2 = ScatterTrace.builder(x, segment)\n",
    "        .mode(ScatterTrace.Mode.LINE)\n",
    "        .name(trace2Name)\n",
    "        .build();\n",
    "\n",
    "    Layout layout = Layout.builder()\n",
    "        .height(height)\n",
    "        .width(width)\n",
    "        .showLegend(true)\n",
    "        .xAxis(Axis.builder().title(xLabel).build())\n",
    "        .yAxis(Axis.builder().title(yLabel).build())\n",
    "        .build();\n",
    "\n",
    "    return new Figure(layout, trace, trace2);\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 14
   },
   "source": [
    "Now we can plot the function $u = f(x)$ and its tangent line $y = 2x - 3$ at $x=1$, where the coefficient $2$ is the slope of the tangent line.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NDArray X = manager.arange(0f, 3f, 0.1f, DataType.FLOAT64);\n",
    "double[] x = X.toDoubleArray();\n",
    "\n",
    "double[] fx = new double[x.length];\n",
    "for (int i=0; i < x.length; i++) {\n",
    "    fx[i] = f.apply(x[i]);\n",
    "}\n",
    "\n",
    "\n",
    "double[] fg = new double[x.length];\n",
    "for (int i=0; i < x.length; i++) {\n",
    "    fg[i] = 2*x[i]-3;\n",
    "}\n",
    "\n",
    "plotLineAndSegment(x, fx, fg, \"f(x)\", \"Tangent line(x=1)\", \"x\", \"f(x)\", 700, 500)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 16
   },
   "source": [
    "## Partial Derivatives\n",
    "\n",
    "So far we have dealt with the differentiation of functions of just one variable.\n",
    "In deep learning, functions often depend on *many* variables.\n",
    "Thus, we need to extend the ideas of differentiation to these *multivariate* functions.\n",
    "\n",
    "\n",
    "Let $y = f(x_1, x_2, \\ldots, x_n)$ be a function with $n$ variables. The *partial derivative* of $y$ with respect to its $i^\\mathrm{th}$  parameter $x_i$ is\n",
    "\n",
    "$$ \\frac{\\partial y}{\\partial x_i} = \\lim_{h \\rightarrow 0} \\frac{f(x_1, \\ldots, x_{i-1}, x_i+h, x_{i+1}, \\ldots, x_n) - f(x_1, \\ldots, x_i, \\ldots, x_n)}{h}.$$\n",
    "\n",
    "\n",
    "To calculate $\\frac{\\partial y}{\\partial x_i}$, we can simply treat $x_1, \\ldots, x_{i-1}, x_{i+1}, \\ldots, x_n$ as constants and calculate the derivative of $y$ with respect to $x_i$.\n",
    "For notation of partial derivatives, the following are equivalent:\n",
    "\n",
    "$$\\frac{\\partial y}{\\partial x_i} = \\frac{\\partial f}{\\partial x_i} = f_{x_i} = f_i = D_i f = D_{x_i} f.$$\n",
    "\n",
    "\n",
    "## Gradients\n",
    "\n",
    "We can concatenate partial derivatives of a multivariate function with respect to all its variables to obtain the *gradient* vector of the function.\n",
    "Suppose that the input of function $f: \\mathbb{R}^n \\rightarrow \\mathbb{R}$ is an $n$-dimensional vector $\\mathbf{x} = [x_1, x_2, \\ldots, x_n]^\\top$ and the output is a scalar. The gradient of the function $f(\\mathbf{x})$ with respect to $\\mathbf{x}$ is a vector of $n$ partial derivatives:\n",
    "\n",
    "$$\\nabla_{\\mathbf{x}} f(\\mathbf{x}) = \\bigg[\\frac{\\partial f(\\mathbf{x})}{\\partial x_1}, \\frac{\\partial f(\\mathbf{x})}{\\partial x_2}, \\ldots, \\frac{\\partial f(\\mathbf{x})}{\\partial x_n}\\bigg]^\\top,$$\n",
    "\n",
    "where $\\nabla_{\\mathbf{x}} f(\\mathbf{x})$ is often replaced by $\\nabla f(\\mathbf{x})$ when there is no ambiguity.\n",
    "\n",
    "Let $\\mathbf{x}$ be an $n$-dimensional vector, the following rules are often used when differentiating multivariate functions:\n",
    "\n",
    "* For all $\\mathbf{A} \\in \\mathbb{R}^{m \\times n}$, $\\nabla_{\\mathbf{x}} \\mathbf{A} \\mathbf{x} = \\mathbf{A}^\\top$,\n",
    "* For all  $\\mathbf{A} \\in \\mathbb{R}^{n \\times m}$, $\\nabla_{\\mathbf{x}} \\mathbf{x}^\\top \\mathbf{A}  = \\mathbf{A}$,\n",
    "* For all  $\\mathbf{A} \\in \\mathbb{R}^{n \\times n}$, $\\nabla_{\\mathbf{x}} \\mathbf{x}^\\top \\mathbf{A} \\mathbf{x}  = (\\mathbf{A} + \\mathbf{A}^\\top)\\mathbf{x}$,\n",
    "* $\\nabla_{\\mathbf{x}} \\|\\mathbf{x} \\|^2 = \\nabla_{\\mathbf{x}} \\mathbf{x}^\\top \\mathbf{x} = 2\\mathbf{x}$.\n",
    "\n",
    "Similarly, for any matrix $\\mathbf{X}$, we have $\\nabla_{\\mathbf{X}} \\|\\mathbf{X} \\|_F^2 = 2\\mathbf{X}$. As we will see later, gradients are useful for designing optimization algorithms in deep learning.\n",
    "\n",
    "\n",
    "## Chain Rule\n",
    "\n",
    "However, such gradients can be hard to find.\n",
    "This is because multivariate functions in deep learning are often *composite*,\n",
    "so we may not apply any of the aforementioned rules to differentiate these functions.\n",
    "Fortunately, the *chain rule* enables us to differentiate composite functions.\n",
    "\n",
    "Let us first consider functions of a single variable.\n",
    "Suppose that functions $y=f(u)$ and $u=g(x)$ are both differentiable, then the chain rule states that\n",
    "\n",
    "$$\\frac{dy}{dx} = \\frac{dy}{du} \\frac{du}{dx}.$$\n",
    "\n",
    "Now let us turn our attention to a more general scenario\n",
    "where functions have an arbitrary number of variables.\n",
    "Suppose that the differentiable function $y$ has variables\n",
    "$u_1, u_2, \\ldots, u_m$, where each differentiable function $u_i$\n",
    "has variables $x_1, x_2, \\ldots, x_n$.\n",
    "Note that $y$ is a function of $x_1, x_2, \\ldots, x_n$.\n",
    "Then the chain rule gives\n",
    "\n",
    "$$\\frac{dy}{dx_i} = \\frac{dy}{du_1} \\frac{du_1}{dx_i} + \\frac{dy}{du_2} \\frac{du_2}{dx_i} + \\cdots + \\frac{dy}{du_m} \\frac{du_m}{dx_i}$$\n",
    "\n",
    "for any $i = 1, 2, \\ldots, n$.\n",
    "\n",
    "\n",
    "\n",
    "## Summary\n",
    "\n",
    "\n",
    "* Differential calculus and integral calculus are two branches of calculus, where the former can be applied to the ubiquitous optimization problems in deep learning.\n",
    "* A derivative can be interpreted as the instantaneous rate of change of a function with respect to its variable. It is also the slope of the tangent line to the curve of the function.\n",
    "* A gradient is a vector whose components are the partial derivatives of a multivariate function with respect to all its variables.\n",
    "* The chain rule enables us to differentiate composite functions.\n",
    "\n",
    "\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. Plot the function $y = f(x) = x^3 - \\frac{1}{x}$ and its tangent line when $x = 1$.\n",
    "1. Find the gradient of the function $f(\\mathbf{x}) = 3x_1^2 + 5e^{x_2}$.\n",
    "1. What is the gradient of the function $f(\\mathbf{x}) = \\|\\mathbf{x}\\|_2$?\n",
    "1. Can you write out the chain rule for the case where $u = f(x, y, z)$ and $x = x(a, b)$, $y = y(a, b)$, and $z = z(a, b)$?\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Java",
   "language": "java",
   "name": "java"
  },
  "language_info": {
   "codemirror_mode": "java",
   "file_extension": ".jshell",
   "mimetype": "text/x-java-source",
   "name": "Java",
   "pygments_lexer": "java",
   "version": "11.0.9.1+1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
